<template>
  <!-- 分享选项弹窗 -->
  <su-popup
    :show="localShow"
    @update:show="(val) => $emit('update:show', val)"
    position="bottom"
    round="20"
    :overlay="true"
    @close="handleClose"
  >
    <view class="share-popup">
      <view class="share-popup__title">转发</view>
      <view class="share-popup__content ss-flex justify-around">
        <view class="share-item ss-flex-col justify-center align-center">
          <button
            open-type="share"
            class="share-button"
          >
            <image
              class="share-icon wechat-icon"
              src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250311/8ee6ff4103e85c07d876bc140ab5700c.png"
              mode=""
            />
            <view class="share-text">微信好友</view>
          </button>
        </view>
        <view class="share-item ss-flex-col justify-center align-center">
          <button
            class="share-button"
            @click="handleMomentsShare"
          >
            <image
              class="share-icon moments-icon"
              src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250311/118c02ac304c0ed6fa4a7143d4f48a76.png"
              mode=""
            />
            <view class="share-text">朋友圈</view>
          </button>
        </view>
        <view class="share-item ss-flex-col justify-center align-center">
          <button
            class="share-button"
            @click="shear_show('share')"
          >
            <image
              class="share-icon qrcode-icon"
              src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/sns/20250316/8edc4c4685d7cef0b4706eaabc8bebea.png"
              mode=""
            />
            <view class="share-text">私信</view>
          </button>
        </view>
      </view>
      <view
        class="share-popup__cancel ss-m-t-20"
        @click="handleClose"
      >取消</view>
    </view>
  </su-popup>

  <!-- 私信好友弹窗 -->
  <su-popup
    :show="show_popup"
    ref="sharePopup"
    type="bottom"
    background-color="#fff"
  >
    <view class="share_popup">
      <!-- 搜索框 -->
      <view class="search-box">
        <input
          type="text"
          placeholder="搜索"
          class="search-input"
          v-model="searchKeyword"
          @confirm="get_share_list"
          @blur="get_share_list"
        />
      </view>

      <!-- 分类标签栏 -->
      <view class="tab-bar">
        <text
          v-for="(item, index) in tabList"
          :key="index"
          :class="['tab-item', currentTab === index ? 'active' : '']"
          @click="switchTab(index)"
        >{{ item }}</text>
      </view>

      <!-- 好友列表 -->
      <scroll-view
        scroll-y
        class="friend-list"
        @scrolltolower="load_more"
      >
        <view
          class="friend-item"
          v-for="(item, index) in list"
          :key="index"
        >
          <image
            class="friend-avatar"
            :src="item.avatar"
            mode="aspectFill"
          ></image>
          <view class="friend-info">
            <text class="friend-name">{{ item.nickname }}</text>
          </view>
          <button
            @click="shend_share(item)"
            class="send-btn"
          >发送</button>
        </view>
        <div class="no_more">没有更多了</div>
      </scroll-view>
      <!-- 底部取消按钮 -->
      <view
        class="cancel-btn"
        @click="show_popup = false"
      >
        <text>取消</text>
      </view>
    </view>
  </su-popup>
</template>



<script>
import API from '@/association/api';
import sheep from '@/sheep';
import { showAuthModal } from '@/sheep/hooks/useModal';
export default {
  name: 'PopupShare',

  props: {
    show: {
      type: Boolean,
      default: false,
    },
    findId: {
      type: [String, Number],
      default: '',
    },
  },

  data () {
    return {
      localShow: this.show,
      searchKeyword: '',
      currentTab: 0,
      tabList: ['好友', '群聊', '我的团队', '我的商户',],
      list: [],
      share_info: {},
      // 添加分页相关数据
      page: 1,
      pageSize: 10,
      has_more: true,
      loading: false,
      show_popup: false
    };
  },

  watch: {
    show (newVal) {
      this.localShow = newVal;
      if (newVal) {
        this.get_share_list();
      }
    },
  },

  mounted () {
    let user_info = uni.getStorageSync('user-store');
    user_info = JSON.parse(user_info);

    if (user_info?.userInfo?.id) {
      this.user_id = user_info.userInfo.id;
    }
  },

  methods: {
    load_more () {
      if (this.has_more) {
        this.page++;
        this.get_share_list();
      }
    },
    shear_show (type) {
      if (type == 'share') {
        this.handleClose();
        if (!sheep.$store('user').isLogin) {
          showAuthModal();
          return;
        }
      }
      this.show_popup = true;
      // this.$refs.sharePopup.open('bottom');
    },
    shend_share (item) {
      let params;

      if (this.currentTab == 0) {
        params = {
          pattern: 'msg',
          group_id: '',
          to_account: item.id,
          find_id: this.findId,
        };
      } else if (this.currentTab == 1) {
        params = {
          pattern: 'group',
          group_id: item.id,
          to_account: '',
          find_id: this.findId,
        };
      } else if (this.currentTab == 2) {
        params = {
          pattern: 'group',
          group_id: item.id,
          to_account: '',
          find_id: this.findId,
        };
      } else if (this.currentTab == 3) {
        params = {
          pattern: 'group',
          group_id: item.id,
          to_account: '',
          find_id: this.findId,
        };
      }

      uni.showLoading({
        title: '发送中...',
        mask: true,
      });

      API.send_share(params)
        .then((res) => {
          uni.hideLoading();
          if (res.code == 1) {
            setTimeout(() => {
              uni.showModal({
                title: '提示',
                content: '发送成功',
                cancelText: '继续分享',
                confirmText: '前往聊天',
                success: async (res) => {
                  if (res.confirm) {

                    if (this.currentTab == 0) {
                      let to = {
                        aim: 'message',
                        service: {
                          mobile: item.mobile,
                        },
                      };
                      const urlJson = encodeURIComponent(JSON.stringify(to))
                      uni.navigateTo({
                        url: '/im/pages/web?to=' + urlJson,
                      });
                    } else {
                      let to = {
                        aim: 'groupMessage',
                        service: {
                          mobile: `GROUP${item.id}`,
                        }
                      }
                      const urlJson = encodeURIComponent(JSON.stringify(to))
                      uni.navigateTo({
                        url: "/im/pages/web?to=" + urlJson
                      })
                    }

                  } else if (res.cancel) {
                    console.log('用户点击了取消按钮，什么都不做');
                  }
                },
              });
            }, 200)
          }
        })
        .catch((err) => {
          // 发生错误时也要隐藏loading
          uni.hideLoading();
          uni.showToast({
            title: '发送失败',
            icon: 'error',
          });
        });
    },
    get_share_list () {
      console.log(this.tabList[this.currentTab], 'this.tabList[this.currentTab]');

      API.shareList({
        search: this.searchKeyword,
        type: this.tabList[this.currentTab],
        page: this.page,
        list_rows: 100,
      }).then((res) => {
        if (res.data.data.current_page == res.data.data.last_page) {
          this.has_more = false;
        }
        this.list = res.data.data.data;
      });
    },

    handleClose () {
      this.$emit('update:show', false);
    },

    // 添加其他必要的方法
    handleMomentsShare () {
      uni.showToast({
        title: '请点击右上角选择复制链接分享朋友圈',
        icon: 'none',
      });
      this.handleClose();
    },

    handlePrivateMessage () {
      this.handleClose();
      this.show_popup = true
      // this.$refs.sharePopup.open('bottom');
    },

    closeMessagePopup () {
      this.show_popup = false
      // this.$refs.sharePopup.close();
    },

    handleSearch () {
      this.getShareList();
    },

    switchTab (index) {
      this.has_more = true;
      this.currentTab = index;
      this.get_share_list();
      // this.currentTab = index;
      // if (index === 0) {
      //   this.list = this.share_info.friends;
      // } else if (index === 1) {
      //   this.list = this.share_info.groups;
      // } else if (index === 2) {
      //   this.list = this.share_info.shop_groups;
      // } else if (index === 3) {
      //   this.list = this.share_info.maker;
      // }
    },

    async getShareList () {
      const res = await API.shareList({
        search: this.searchKeyword,
        user_id: uni.getStorageSync('user_id'),
      });
      if (res.code === 1) {
        this.share_info = res.data;
        this.switchTab(this.currentTab);
      }
    },

    async handleSend (item) {
      const params = {
        pattern: this.currentTab === 0 ? 'msg' : 'group',
        group_id: this.currentTab === 0 ? '' : item.id,
        to_account: this.currentTab === 0 ? item.id : '',
        find_id: this.findId,
      };

      uni.showLoading({
        title: '发送中...',
        mask: true,
      });

      API.send_share(params)
        .then((res) => {
          uni.hideLoading();
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              icon: 'success',
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          // 发生错误时也要隐藏loading
          uni.hideLoading();
          uni.showToast({
            title: '发送失败',
            icon: 'error',
          });
        });

    },
  },
};
</script>

<style lang="less" scoped>
.no_more {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  padding: 20rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.share-popup {
  padding: 30rpx;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;

  &__title {
    font-size: 32rpx;
    text-align: center;
    color: #333;
    margin-bottom: 40rpx;
  }

  &__content {
    padding: 20rpx 0;
  }

  &__cancel {
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    font-size: 32rpx;
    color: #333;
    border-top: 1rpx solid #eee;
  }

  .share-item {
    padding: 10rpx;

    .share-button {
      background: transparent;
      border: none;
      padding: 0;
      margin: 0;
      line-height: normal;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &::after {
        border: none;
      }
    }

    .share-icon {
      width: 80rpx;
      height: 80rpx;
      margin-bottom: 20rpx;
    }

    .share-text {
      font-size: 28rpx;
      color: #333;
      margin-top: 10rpx;
    }
  }
}

.share_popup {
  background-color: #fff;
  height: 60vh;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx 30rpx 130rpx;
  display: flex;
  flex-direction: column;
  position: relative;

  .search-box {
    margin-bottom: 20rpx;
    display: flex;
    padding: 0 20rpx;

    .search-input {
      flex: 1;
      background-color: #f5f5f5;
      height: 70rpx;
      border-radius: 35rpx;
      padding: 0 30rpx;
      font-size: 28rpx;
    }
  }

  .tab-bar {
    display: flex;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;
    flex-direction: row;
    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #666;

      &.active {
        color: #333;
        font-weight: bold;
      }
    }
  }

  .friend-list {
    flex: 1;
    height: calc(100% - 200rpx);
    overflow-y: auto;

    .friend-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      flex-direction: row;

      .friend-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 10rpx;
      }

      .friend-info {
        flex: 1;
        padding: 0 20rpx;

        .friend-name {
          font-size: 28rpx;
          color: #333;
        }
      }

      .send-btn {
        width: 120rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        background-color: #07c160;
        color: #fff;
        font-size: 28rpx;
        border-radius: 30rpx;
        padding: 0;
      }
    }
  }

  .cancel-btn {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 32rpx;
    color: #333;
    border-top: 1rpx solid #eee;
    background: #fff;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
  }
}
</style>